package so.ruo.api;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

public class Tools {

	/**
	 * 
	 * 获取真实链接
	 * 
	 * 
	 * 
	 * @param url
	 * 
	 * @return
	 * 
	 * @throws IOException
	 * 
	 * @throws ClientProtocolException
	 */

	public String getRealUrl(String url) throws IOException {

		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpGet httpget = new HttpGet(url);

		HttpContext localContext = new BasicHttpContext();

		CloseableHttpResponse response = httpclient.execute(httpget, localContext);

		try {

			int status = response.getStatusLine().getStatusCode();

			if (status == 404) {

				HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

				HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);

				return target.toString() + req.getURI();

			}

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			response.close();

		}

		return null;

	}

	/**
	 * 打印cookies
	 */
	public static void printCookies(List<Cookie> cookies) {
		if (cookies.isEmpty()) {
			System.out.println("------------------is empty------------------");
		} else {
			System.out.println("------------------cookies size: " + cookies.size() + "------------------");
			for (int i = 0; i < cookies.size(); i++) {
				System.out.println(cookies.get(i).getName() + "=" + cookies.get(i).getValue());
			}
		}
	}
	
	public static void main(String[] args) {
		
		String url="http://news.ifeng.com/a/20150803/44332731_0.shtml";
		
		String result = "";
		String regx1 = "\\/n(.*?).shtml(.*?)";
		Pattern p = Pattern.compile(regx1);
		String text = url.toString();
		Matcher macher = p.matcher(text.replace("news.sohu.com", ""));
		boolean isMacher = macher.find();
		if (isMacher) {
			result = macher.group(1).trim();
		}
		
		System.out.println(result);
		
		
	}

}
